﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using System.Diagnostics;

namespace HappyFrogXna.Miscellaneous
{
    delegate void GameTimerDelegate();

    static class GameTimerCreator
    {
        private static List<HFGameTimer> _timerList = new List<HFGameTimer>();

        public static HFGameTimer CreateTimer()
        {
            for (int i = 0; i < _timerList.Count; ++i)
            {
                if (!_timerList[i].IsRunning)
                {
                    return _timerList[i];
                }
            }
            _timerList.Add(new HFGameTimer());
            return _timerList.Last<HFGameTimer>();
        }

        public static void Update(GameTime gameTime)
        {
            for (int i = 0; i < _timerList.Count; ++i)
            {
                _timerList[i].Update(gameTime);
            }
        }
    }

    class HFGameTimer
    {
        GameTimerDelegate _delegate;
        float _remainTimeInMillisecond;
        public bool IsRunning = false;

        public void SingleShot(float timeInMillisecond, GameTimerDelegate fun)
        {
            _remainTimeInMillisecond = timeInMillisecond;
            _delegate = fun;
            IsRunning = true;
        }

        public void Update(GameTime gameTime)
        {
            if (IsRunning)
            {
                if (_remainTimeInMillisecond < 0)
                {
                    _delegate();
                    IsRunning = false;
                    return;
                }
                _remainTimeInMillisecond -= gameTime.ElapsedGameTime.Milliseconds;
            }
        }
    }
}
